package com.stars.easyms.gateway.swagger;

import com.stars.easyms.gateway.properties.EasyMsGatewayProperties;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * <p>className: SwaggerWebFilter</p>
 * <p>description: Swagger网关层过滤器</p>
 *
 * @author guoguifang
 * @version 1.6.3
 * @date 2020/9/12 11:23 上午
 */
public class EasyMsSwaggerWebFilter implements WebFilter {

    private static final String SWAGGER_URL = "/swagger";

    private static final String SWAGGER_WEBJARS = "/webjars/easyms/";

    private static final String SWAGGER_HTML = "/webjars/easyms/swagger/swagger-ui.html";

    private EasyMsGatewayProperties gatewayProperties;

    public EasyMsSwaggerWebFilter(EasyMsGatewayProperties gatewayProperties) {
        this.gatewayProperties = gatewayProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        if (gatewayProperties.isDebugEnabled()) {

            String servletPath = gatewayProperties.getServletPath();

            // 当前请求路径
            ServerHttpRequest request = exchange.getRequest();
            String currentRequestPath = request.getPath().value();

            // 判断是否是swagger页面
            if (currentRequestPath.equals(servletPath + SWAGGER_URL)) {
                return chain.filter(
                        exchange.mutate().request(
                                request.mutate().path(SWAGGER_HTML)
                                        .build())
                                .build());
            } else if (currentRequestPath.startsWith(servletPath + SWAGGER_WEBJARS)
                    || currentRequestPath.startsWith(servletPath + EasyMsGatewaySwaggerController.GET_SWAGGER_RESOURCES_URL)) {
                return chain.filter(
                        exchange.mutate().request(
                                request.mutate().path(currentRequestPath.substring(servletPath.length()))
                                        .build())
                                .build());
            }
        }
        return chain.filter(exchange);
    }
}
